package wymiana.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import wymiana.domain.Mail;
import wymiana.domain.User;


@Repository
public class MailDao extends GenericDao<Mail> {

	@Autowired
	public MailDao(SessionFactory sf) {
		super(Mail.class, sf);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Mail> getAll() {
		return getHibernateTemplate().find("from Mail mail order by mail.id");
	}

	@SuppressWarnings("unchecked")
	public List<Mail> getBySender(User sender) {
		return getHibernateTemplate()
				.find("from Mail mail where mail.sender=? and mail.trash_sender=0 and mail.deleted_sender=0 ",
						sender);
	}

	@SuppressWarnings("unchecked")
	public List<Mail> getByRecipient(User recipient) {
		return getHibernateTemplate()
				.find("from Mail mail where mail.recipient=? and mail.trash=0 and mail.deleted=0",
						recipient);
	}

	@SuppressWarnings("unchecked")
	public List<Mail> getMailByUserAndId(User user, Long id) {
		return getHibernateTemplate()
				.find("from Mail mail where (mail.recipient=? and mail.id=? and mail.deleted=0) or (mail.sender=? and mail.id=? and mail.deleted_sender=0 )",
						user, id, user, id);

	}

	public Mail get(Long id) {
		return getHibernateTemplate().get(Mail.class, id);
	}

	public Mail delete(Long id) {
		Mail mail = get(id);

		if (mail != null) {
			delete(mail);
		}
		return mail;
	}

	@SuppressWarnings("unchecked")
	public List<Mail> getMailsByTrash(User user) {
		return getHibernateTemplate()
				.find("from Mail mail where (mail.recipient=? and mail.trash=1 and mail.deleted=0) or (mail.sender=? and mail.trash_sender=1 and mail.deleted_sender=0)",
						user, user);

	}

	@SuppressWarnings("unchecked")
	public List getNewMailsCount(User user) {
		return getHibernateTemplate()
				.find("select count(*) from Mail mail where mail.recipient=? and mail.trash=0 and mail.deleted=0 and mail.readed=0 ",
						user);

	}
}
